package com.ximu.test.base.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	
	private static Socket socket;
	
	public static void main(String[] args){
		try{
			System.out.println("开始创建:");
			//1.链接服务端
			socket = new Socket("127.0.0.1",2012);
			class ListenerSocket extends Thread{
				@Override
				public void run() {
					System.out.println("开始监听数据:");
					try{
						BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						String str = socketReader.readLine();
						while(str!=null && !str.equals("quit")){
							System.out.println("Server:"+str);
							str = socketReader.readLine();
						}
						socketReader.close();
						socket.close();
						System.out.println("quit");
					}catch(IOException e){
						System.out.println("错误");
					}
					super.run();
				}

			}
			Thread listenerThread = new Thread(new ListenerSocket());
			listenerThread.start();
			
			//2.得到socket输入
			//BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			//3.得到socket输出
			PrintWriter socketWriter = new PrintWriter(socket.getOutputStream());
			//System.out.println("Server:"+socketReader.readLine());
			BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("等待输入:");
			String inputString  = input.readLine();
			while(!inputString.equals("quit")){
//				System.out.println("Client:"+inputString);
				socketWriter.println(inputString);
				socketWriter.flush();
				inputString = input.readLine();
			}
			//input.close();
			socketWriter.close();
			//socketReader.close();
			socket.close();
		}catch(Exception e){
			System.out.println("错误");
		}
	}
}
